/*
============================================================================
 Name        : TCPSocketReceiver.cpp
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : CTCPSocketReceiver implementation
============================================================================
*/

#include "TCPSocketReceiver.h"
#include <string.h>

CTCPSocketReceiver::CTCPSocketReceiver(MObserver& aObserver, RSocket& aSocket) :
CActive(EPriorityStandard),	iObserver(aObserver), iSocket(aSocket),
		iRecvBuf(0,0,0)// Standard priority
{
	CActiveScheduler::Add(this);				// Add to scheduler
	iBuffPtr = new (ELeave) TUint8[KBuffSizeSOCKET];
}

CTCPSocketReceiver::~CTCPSocketReceiver()
{
	Cancel(); // Cancel any request, if outstanding
	// Delete instance variables if any
	delete iBuffPtr;
}

void CTCPSocketReceiver::Receive()
{
	Cancel();
	// Receive the length of the message
	memset(iBuffPtr,0,KBuffSizeSOCKET);
	iRecvBuf.Set(iBuffPtr, 0, KBuffSizeSOCKET);	
	iSocket.RecvOneOrMore(iRecvBuf, 0, iStatus, iLen);
	SetActive();
}

void CTCPSocketReceiver::DoCancel()
{
	iSocket.CancelRead();
}

void CTCPSocketReceiver::RunL()
{
	TInt err = iStatus.Int();
	if(err==KErrNone)
		{		
		// Notify observer	
		TInt recvLen = iLen();					
		iRecvBuf.Set(iBuffPtr, recvLen, recvLen);
		iObserver.OnReceiveL(iRecvBuf, err);
			
		}
	else
		{
	this->iObserver.OnReceiveL(KNullDesC8(),err);
		}	
}

